package server;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;

import com.bn.activemq.base.MqType;

import server.bean.Message;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.List;


public class BusiHandler extends SimpleChannelHandler {
	DatagramSocket ds;
	private InternalLogger logger;

	public BusiHandler() {
		super();
		logger = InternalLoggerFactory.getInstance(getClass());

//		try {
//			ds = new DatagramSocket(9901, InetAddress.getByName("117.78.34.2"));
//		} catch (SocketException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (UnknownHostException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
	
	/**
	 * 临时记录这是解析出来的第几条报文
	 */
	public int count = 0;
	
//    @Override
//    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
//        // TODO Auto-generated method stub
//        Message msg = (Message) e.getMessage();
//        switch (msg.getMsgId()) {
//            case 0x1001:
//                login(msg, ctx, e);
//                break;
//            case 0x1005:
//                System.out.println("主链路连接保持请求消息。");
//                heartBeat(msg, ctx, e);
//                break;
//            case 0x1200:
//                System.out.println("主链路动态信息交换消息");
//                System.out.println("msg:" + msg.toString());
//                parseGPS(msg, ctx, e);
//                break;
//            default:
//                break;
//        }
//    }
    
	@Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		logger.info("开始循环，解析报文数据体");
		List<Message> msgList = (List<Message>) e.getMessage();
//    	List<String> msgList = (List<String>) e.getMessage();
//    	for (String string : msgList) {
//    		logger.info("busi拿到单条报文内容：" + string);
//    		logger.info("先直接发到MQ-------------------------------" + ++count);
//    		producer.sendMessage(string);
//		}
    	
    	for (Message msg : msgList) {
	        switch (msg.getMsgId()) {
	            case 0x1001:
	                login(msg, ctx, e);
	                break;
	            case 0x1005:
	                logger.info("此报文为0x1005主链路连接保持请求消息。");
	                heartBeat(msg, ctx, e);
	                break;
	            case 0x1200:
	            	logger.info("此报文为0x1200主链路动态信息交换消息");
	                parseGPS(msg, ctx, e);
	                break;
	            default:
	                break;
	        }
        }
    	logger.info("+----------------------------------------------一个数据包解析结束了---------------------------------------------------------");
    	System.out.println("+----------------------------------------------一个数据包解析结束了---------------------------------------------------------");
	}

    private void parseGPS(Message msg, ChannelHandlerContext ctx, MessageEvent e) {
    	logger.info("开始解析报文，报文内容msg:" + msg.toString());
    	logger.info("+-------------------------------------------------------------------------------------------------------");
        String carNum = msg.getMsgBody().readBytes(21).toString(Charset.forName("GBK")).trim();
        logger.info("|carNum:" + carNum);
        
        byte carColor = msg.getMsgBody().readByte();
        logger.info("|carColor:" + carColor);
        
        int dataType = msg.getMsgBody().readUnsignedShort();
        logger.info("|dataType:" + dataType);
        
        int capacity = msg.getMsgBody().readInt();
        logger.info("|capacity:" + capacity);
        
        int gnssCount = 0;
        if(dataType == 0x1203){//1203比1202需要多读一个字节
        	gnssCount = msg.getMsgBody().readByte();
        	logger.info("|gnssCount:" + gnssCount);
        }
        
        byte encryptKey = msg.getMsgBody().readByte();
        logger.info("|encryptKey:" + encryptKey);
        
        byte day = msg.getMsgBody().readByte();
        logger.info("|day:" + day);
        
        byte month = msg.getMsgBody().readByte();
        logger.info("|month:" + month);
        
//        String year = msg.getMsgBody().readBytes(2).toString(Charset.forName("GBK"));
        int year = msg.getMsgBody().readShort();
        logger.info("|year:" + year);
        
        byte hour = msg.getMsgBody().readByte();
        logger.info("|hour:" + hour);
        
        byte minute = msg.getMsgBody().readByte();
        logger.info("|minute:" + minute);
        
        byte second = msg.getMsgBody().readByte();
        logger.info("|second:" + second);
        
        int lon = msg.getMsgBody().readInt();
        int lat = msg.getMsgBody().readInt();
        logger.info("|lon:" + lon);
        logger.info("|lat:" + lat);
        
        String lonStr = lon+"";
        int lonStrLen = lonStr.length();
        String latStr = lat+"";
        int latStrLen = latStr.length();
        
        try{
        	lonStr = lonStr.substring(0, lonStrLen-6) + "." + lonStr.substring(lonStrLen-6);
        	latStr = latStr.substring(0, latStrLen-6) + "." + latStr.substring(latStrLen-6);
        }catch(StringIndexOutOfBoundsException sie){
        	logger.warn("+----------------------------------------------经纬度有异常值，报文废弃，该条报文解析结束" + ++count, sie);
        	return;
        }
        
        logger.info("|lon:" + lonStr + "（添加小数点）");
        logger.info("|lat:" + latStr + "（添加小数点）");
        
        int speed1 = msg.getMsgBody().readShort();//指卫星定位车载终端设备上传的行车速度信息
        logger.info("|speed1:" + speed1);
        
        int speed2 = msg.getMsgBody().readShort();//行驶记录速度，指车辆行驶记录设备上传的行车速度信息
        logger.info("|speed2:" + speed2);
        
        int mileage = msg.getMsgBody().readInt();//车辆当前总里程数
        logger.info("|mileage:" + mileage);
        
        int direction = msg.getMsgBody().readShort();
        logger.info("|direction:" + direction);
        
        int altitude = msg.getMsgBody().readShort();
        logger.info("|altitude:" + altitude);
        
        int state = msg.getMsgBody().readInt();
        logger.info("|state:" + state);
        
//        int alarm = msg.getMsgBody().readInt();
//        logger.info("|alarm:" + alarm);
        
        logger.info("+----------------------------------------------一条报文解析结束了---------------------------------------------------------" + ++count);
        
        StringBuffer sb = new StringBuffer();
        sb.append("02,");
        sb.append(carNum + ",");
        sb.append("1,");
        sb.append(year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second+",");
        sb.append(lonStr+",");
        sb.append(latStr+",");
        sb.append("0,");
        sb.append("4326,");//x、y 值所采用的空间参考
        sb.append("0,");//x 方向速度
        sb.append("0,");//y 方向速度
        sb.append(speed1+",");//速度
        sb.append(direction+",");//方向
        sb.append(gnssCount+",");//定位质量
        sb.append("1,");//定位质量
        sb.append("BJBN");//定位质量
        
        logger.info("将解析结果发往117.78.34.2：9901-----"+sb.toString());
//        sendData(sb.toString());
        

        
		
    }

    /**
     * 用udp将报文发给重庆给的ip和端口
     */
    private void sendData(String message){
    	try {
			byte[] sendBytes = message.getBytes("utf-8");
			DatagramSocket ds = new DatagramSocket();
			DatagramPacket dp = new DatagramPacket(sendBytes, sendBytes.length,
					InetAddress.getByName("117.78.34.2"), 9901);
			ds.send(dp);
			ds.close();// 关闭连接
		} catch (IOException e3) {
			e3.printStackTrace();
		}
    }
    
    private void login(Message msg, ChannelHandlerContext ctx, MessageEvent e) {
//        int userId = msg.getMsgBody().readInt();
//        String passWord = msg.getMsgBody().readBytes(8).toString(Charset.forName("GBK"));
//        String ip = msg.getMsgBody().readBytes(32).toString(Charset.forName("GBK"));
//        int port = msg.getMsgBody().readUnsignedShort();
//        msg.getMsgBody().clear();
//        System.out.println("userId:" + userId);
//        System.out.println("passWord:" + passWord);
//        System.out.println("ip:" + ip);
//        System.out.println("port:" + port);

        Message msgRep = new Message(0x1002);
        ChannelBuffer buffer = ChannelBuffers.buffer(5);
        buffer.writeByte(0x00);

        //校验码，临时写死
        buffer.writeInt(1111);
        msgRep.setMsgBody(buffer);
        ChannelFuture f = e.getChannel().write(msgRep);

        // f.addListener(ChannelFutureListener.CLOSE);
    }

    private void heartBeat(Message msg, ChannelHandlerContext ctx, MessageEvent e) {
        Message msgRep = new Message(0x1006);
        ChannelBuffer buffer = ChannelBuffers.buffer(0);
        msgRep.setMsgBody(buffer);
        ChannelFuture f = e.getChannel().write(msgRep);
    }
    
}